import { observable, computed, action } from 'mobx'
import { message } from 'antd'
import { StoreModule } from '@/utils/mobx-store'
import { axiosInstance, withProxy } from '@/utils/http'
import { getEggCookieToken } from '@/utils'

const EGG_TOKEN_KEY = 'x-csrf-token'

const RESPONSE_CODES = {
  SUCCESS: 2000,
}

class Request extends StoreModule {
  @observable requestCount = 0

  @computed
  get isFetching() {
    return this.requestCount > 0
  }

  @action
  _onRequest = (config = {}) => {
    // useLoading
    // 自定义的配置项,表示是否使用默认的全屏loading遮罩层,默认为true
    // useError
    // 自定义的配置项,表示是否在接口报错时,弹出提示框,默认为true
    let { url = '', headers = {}, useLoading = true, useError = true } = config
    if (useLoading) {
      this.requestCount++
    }

    const token = getEggCookieToken()
    !!token && (headers[EGG_TOKEN_KEY] = token)

    url = withProxy(url)

    return { ...config, url, headers, useLoading, useError }
  }

  @action
  _onResponse = (response = {}) => {
    const { useLoading, useError } = response.config

    if (useLoading) {
      this.requestCount--
    }

    if (!response.data || response.data.code !== RESPONSE_CODES.SUCCESS) {
      if (useError) {
        message.error(response.data && response.data.msg ? response.data.msg : '服务器错误')
      }
      return Promise.reject(response.data)
    }

    return response.data
  }

  @action
  _onResponseError = (err = null) => {
    const { useLoading, useError } = err.config
    if (useLoading) {
      this.requestCount--
    }

    if (useError) {
      message.error(err.data && err.data.msg ? err.data.msg : '服务器错误')
    }

    return Promise.reject(err)
  }
}

// 在这里使用拦截器关联store
const requestStore = new Request()
axiosInstance.interceptors.request.use(requestStore._onRequest)
axiosInstance.interceptors.response.use(requestStore._onResponse, requestStore._onResponseError)

export default requestStore
